package com.escool.controller;

import java.text.SimpleDateFormat;

import com.escool.model.SgMensajes;
import com.escool.model.SgMensajesEnv;
import com.escool.model.VwAlumnosUsuario;
import com.escool.model.VwAlumnosUsuarioId;
import com.escool.model.VwProfesorseccion;
import com.escool.service.FindService;
import com.escool.service.SendMailService;
import com.escool.service.TipoRecordService;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import utils.SendMail;

import com.escool.dto.MailInfoDTO;



@Controller
public class SendMailController {
	
	@Autowired
	SendMailService SendMailService;
	@Autowired
	FindService findService;
	@Autowired
	TipoRecordService tipoRecordService;
	
	
	
	//Comunicacion Alumno Profesor
	@RequestMapping(value = "showSendMailAlumnoProf")
	public String showSendMailAlumnoProf( Map<String, Object> map){
		try{
		User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();	
		map.put("sendMailDto", new MailInfoDTO());
		map.put("listsendMailDto",SendMailService.listSgMensajes(user.getUsername()) );
		map.put("listsendMailVW",findService.listVwMensajesEnv(user.getUsername()));
		map.put("listMaterias",findService.listVwAlumnosMateria(user.getUsername()));
		return "/showSendMailAlumnoProf";
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return "/login";
	}
	
	//Inserta aviso
		@RequestMapping(value = "sendSendMailAlumnoProf", method = RequestMethod.POST)
		public String sendSendMailAlumnoProf(@ModelAttribute("sendMailDto") @Valid MailInfoDTO sendMailDto, BindingResult result, Map<String, Object> map){
			try{				
				sendMailDto.setCodigoMensaje("CM");
				sendMailDto.setTipoEnvio("3");			
					sendMailDto.setTo(getall(sendMailDto));			
				
				sendMailMany(sendMailDto);			
				//SendMail sendMail = new SendMail(sendMailDto.getTo(),sendMailDto.getAsunto(),sendMailDto.getMsg());					
			}
			catch(Exception ex){
				ex.printStackTrace();
			}
			return "redirect:/showSendMailAviso";
		}
	
	//Controler para el envio de Foros
	@RequestMapping(value = "showSendMailForo")
	public String showSendMailForo( Map<String, Object> map){
		try{
			User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();	
		map.put("sendMailDto", new MailInfoDTO());
		map.put("listsendMailDto",SendMailService.listSgMensajes(user.getUsername()) );
		map.put("listsendMailVW",findService.listVwMensajesEnv(user.getUsername()));
		
		return "/showSendMailForo";
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return "/login";
	}
	
	
	//Controler para el envio de Mensajes en aviso
	@RequestMapping(value = "showSendMailAviso")
	public String showSendMailAviso( Map<String, Object> map){
		try{
			User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();	
		map.put("sendMailDto", new MailInfoDTO());		
		map.put("listSecciones",findService.listSeccionedRot(user.getUsername()));
		map.put("listsendMailDto",SendMailService.listSgMensajesEnv(user.getUsername()) );
		map.put("listsendMailVW",findService.listVwMensajesEnv(user.getUsername()));
		return "/showSendMailAviso";
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return "/login";
	}
	
	@RequestMapping(value = "showSendMail")
	public String showSendMail( Map<String, Object> map){
		try{
			User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();	
		map.put("sendMailDto", new MailInfoDTO());
		map.put("listsendMailDto",SendMailService.listSgMensajes(user.getUsername()) );
		map.put("listsendMailVW",findService.listVwMensajesEnv(user.getUsername()));
		
		return "/showSendMail";
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return "/login";
	}
	
	
	@RequestMapping(value = "sendSendMail", method = RequestMethod.POST)
	public String sendSendMail(@ModelAttribute("sendMailDto") @Valid MailInfoDTO sendMailDto, BindingResult result, Map<String, Object> map){
		try{				
			sendMailDto.setCodigoMensaje("MJ");
			sendMailMany(sendMailDto);			
			//SendMail sendMail = new SendMail(sendMailDto.getTo(),sendMailDto.getAsunto(),sendMailDto.getMsg());					
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return "redirect:/showSendMail";
	}
	//Inserta aviso
	@RequestMapping(value = "sendSendMailAviso", method = RequestMethod.POST)
	public String sendSendMailAviso(@ModelAttribute("sendMailDto") @Valid MailInfoDTO sendMailDto, BindingResult result, Map<String, Object> map){
		try{				
			sendMailDto.setCodigoMensaje("AV");
			if(!sendMailDto.isCheckBtn()){				
				sendMailDto.setTo(getallVWUser(sendMailDto));			
			}
			sendMailMany(sendMailDto);			
			//SendMail sendMail = new SendMail(sendMailDto.getTo(),sendMailDto.getAsunto(),sendMailDto.getMsg());					
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return "redirect:/showSendMailAviso";
	}
	
	//Inserta Foro
		@RequestMapping(value = "sendSendMailForo", method = RequestMethod.POST)
		public String sendSendMailForo(@ModelAttribute("sendMailDto") @Valid MailInfoDTO sendMailDto, BindingResult result, Map<String, Object> map){
			try{				
				sendMailDto.setCodigoMensaje("FO");
				sendMailMany(sendMailDto);			
				//SendMail sendMail = new SendMail(sendMailDto.getTo(),sendMailDto.getAsunto(),sendMailDto.getMsg());					
			}
			catch(Exception ex){
				ex.printStackTrace();
			}
			return "redirect:/showSendMailForo";
		}
	
	
	@RequestMapping(value = "sendSendMailResponse", method = RequestMethod.POST)
	public String sendSendMailResponse(@ModelAttribute("sendMailDto") @Valid MailInfoDTO sendMailDto, BindingResult result, Map<String, Object> map){
		try{				
			
			sendMailUne(sendMailDto);			
			//SendMail sendMail = new SendMail(sendMailDto.getTo(),sendMailDto.getAsunto(),sendMailDto.getMsg());					
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return "redirect:/showSendMail";
	}
	
	@RequestMapping(value = "sendSendMailComunicacion", method = RequestMethod.POST)
	public String sendSendMailComunicacion(@ModelAttribute("sendMailDto") @Valid MailInfoDTO sendMailDto, BindingResult result, Map<String, Object> map){
		System.out.println("id seccion " + sendMailDto.getSeccion());
		System.out.println("id codigo  " + sendMailDto.getCodigoMensaje());
		try{				
			sendMailDto.setCodigoMensaje("CM");
			
			if(!sendMailDto.isCheckBtn()){				
				sendMailDto.setTo(getall(sendMailDto));			
			}
			sendMailMany(sendMailDto);
			//SendMail sendMail = new SendMail(sendMailDto.getTo(),sendMailDto.getAsunto(),sendMailDto.getMsg());					
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return "redirect:/showComunicacionProfAlumno";
	}
	
	@RequestMapping(value = "delSendMail", method = RequestMethod.POST)
	public String delSendMail(@ModelAttribute("sendMailDto") @Valid MailInfoDTO sendMailDto, BindingResult result, Map<String, Object> map){
		
		
		System.out.println("Id es " + sendMailDto.getIdMensaje());
			if(!result.hasErrors()){
				SendMailService.delete(sendMailDto.getIdMensaje());
			}
			return "redirect:/showInBox";
		
	}
	
	
	
	@RequestMapping(value = "showInBox")
	public String showInBox( Map<String, Object> map){
		try{
			User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	
		map.put("sendMailDto", new MailInfoDTO());
		map.put("listsendMailDto",SendMailService.listSgMensajesRes(user.getUsername()) );
		map.put("listsendMailVW",findService.listVwMensajesEnv(user.getUsername()));
		
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return "/showInBox";
	}
	
	
	//Comunicacion Profesor Alumnos
	@RequestMapping(value = "showComunicacionProfAlumno")
	public String showComunicacionProfAlumno( Map<String, Object> map){
		try{
			User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	
		map.put("sendMailDto", new MailInfoDTO());			
		map.put("listSecciones",findService.listSeccionedRot(user.getUsername()));
		map.put("listsendMailDto",SendMailService.listSgMensajesEnv(user.getUsername()) );
		map.put("listsendMailVW",findService.listVwMensajesEnv(user.getUsername()));
		map.put("tiporecList", tipoRecordService.listAll());
		return "/comunicacionProfesores";
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return "/login";
	}
	
	
	@RequestMapping(value = "showMailResponse", method = RequestMethod.POST)
	public String showMailResponse(@ModelAttribute("sendMailDto") @Valid MailInfoDTO sendMailDto, BindingResult result, Map<String, Object> map){
		SgMensajes msg = SendMailService.find(sendMailDto.getIdMensaje());
		MailInfoDTO dto = new MailInfoDTO();
		dto.setAsunto(msg.getAsunto());
		dto.setTo(msg.getCodigoEmisario());
		
		User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		map.put("sendMailDto",dto);
		map.put("listSecciones",findService.listSeccionedRot(user.getUsername()));
		map.put("listsendMailDto",SendMailService.listSgMensajesEnv(user.getUsername()) );
		map.put("listsendMailVW",findService.listVwMensajesEnv(user.getUsername()));
		System.out.println("Id es " + dto.getIdMensaje());
		System.out.println("Id es " + dto.getAsunto());
		System.out.println("Id es " + dto.getTo());
			
			return "/showSendMailResponse";
		
	}
	
	public void sendMailUne(MailInfoDTO sendMailDto){
		User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		SgMensajes smg = new SgMensajes();			
		smg.setAsunto(sendMailDto.getAsunto());
		smg.setCuerpoMensaje(sendMailDto.getMsg());
		smg.setLeido('0');
		smg.setPara(sendMailDto.getTo());
		smg.setCodigoEmisario(user.getUsername());
		smg.setCodigoReceptor(sendMailDto.getTo());
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy 'a las ' HH:mm:ss");
		String fechaString = sdf.format(date);
		smg.setFechaEnviado(fechaString);
		System.out.println("Enviado " + smg.getCuerpoMensaje());
		SendMailService.add(smg);
		
		SgMensajesEnv env = new SgMensajesEnv();
		env.setAsunto(sendMailDto.getAsunto());
		env.setCuerpoMensaje(sendMailDto.getMsg());
		env.setLeido('0');
		env.setPara(sendMailDto.getTo());
		env.setCodigoEmisario(user.getUsername());

		Date date1 = new Date();
		SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy 'a las ' HH:mm:ss");
		String fechaString1 = sdf1.format(date1);
		env.setFechaEnviado(fechaString1);
		SendMailService.addSgMensajesEnv(env);
	}
	
	public void sendMailMany(MailInfoDTO sendMailDto){
		User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String to = null;
		String userId = null;
		String tipoUsuario = null;
		String nombreCompleto = null;
		String full_mail = null;
		StringTokenizer token = new StringTokenizer(sendMailDto.getTo(), ",");
		while(token.hasMoreTokens()){
			full_mail = token.nextToken();
			StringTokenizer tokenSemiColoms = new StringTokenizer(full_mail, ":");
			if(!(full_mail.equals(" ") || full_mail == null)){
			while(tokenSemiColoms.hasMoreTokens()){
				nombreCompleto = tokenSemiColoms.nextToken();
				to = tokenSemiColoms.nextToken();
				userId = tokenSemiColoms.nextToken();
				tipoUsuario = tokenSemiColoms.nextToken();
			}
			SgMensajes smg = new SgMensajes();	
					
			smg.setAsunto(sendMailDto.getAsunto());
			smg.setCuerpoMensaje(sendMailDto.getMsg());
			smg.setLeido('0');
			smg.setPara(to);
			smg.setCodigoMsj(sendMailDto.getCodigoMensaje());
			smg.setCodigoEmisario(user.getUsername());
			smg.setCodigoReceptor(userId);
			smg.setTipoComunicacion(sendMailDto.getTipoComunicacion());
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy 'a las ' HH:mm:ss");
			String fechaString = sdf.format(date);
			smg.setFechaEnviado(fechaString);
			System.out.println("Enviado " + smg.getCuerpoMensaje());
			SendMailService.add(smg);}
		}
		
		SgMensajesEnv env = new SgMensajesEnv();
		env.setAsunto(sendMailDto.getAsunto());
		env.setCuerpoMensaje(sendMailDto.getMsg());
		env.setLeido('0');
		env.setPara(sendMailDto.getTo());
		env.setCodigoEmisario(user.getUsername());
	    env.setCodigoMsj(sendMailDto.getCodigoMensaje());
	    env.setTipoComunicacion(sendMailDto.getTipoComunicacion());
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy 'a las ' HH:mm:ss");
		String fechaString = sdf.format(date);
		env.setFechaEnviado(fechaString);
		SendMailService.addSgMensajesEnv(env);
	}
	
	
	private String getall(MailInfoDTO sendMailDto){
		String reg = "";
		List datos = null;
		System.out.println("id seccion " + sendMailDto.getSeccion());
		System.out.println("id codigo  " + sendMailDto.getTipoEnvio());
		if(sendMailDto.getTipoEnvio().equals("0")){
			System.out.println("id seccion " + sendMailDto.getSeccion());
			datos = findService.listVwAlumnosUsuario(sendMailDto.getSeccion());
		}
		else{
			datos = findService.listVwAlumnosUsuario(sendMailDto.getSeccion(),sendMailDto.getTipoEnvio());
		}
		if(!datos.isEmpty()){
			for(int i = 0;i<datos.size();i++){
				if(reg.equals("")){
					reg =  (String) datos.get(i);
				}else{
					reg = reg + ","+ datos.get(i);
				}
				System.out.println("no esta bacio"+datos);
			}
			
		}else{
			System.out.println("esta vacio");
		}
		
		return reg; 
	}
	
	//retorna datos de la vista vwuser
	private String getallVWUser(MailInfoDTO sendMailDto){
		String reg = "";
		List datos = null;
		System.out.println("id seccion " + sendMailDto.getSeccion());
		System.out.println("id codigo  " + sendMailDto.getTipoEnvio());
		if(sendMailDto.getTipoEnvio().equals("0")){
			System.out.println("id seccion " + sendMailDto.getSeccion());
			datos = findService.listVwUserTipo();
		}
		else{
			datos = findService.listVwUserTipo(sendMailDto.getTipoEnvio().toString());
		}
		if(!datos.isEmpty()){
			for(int i = 0;i<datos.size();i++){
				if(reg.equals("")){
					reg =  (String) datos.get(i);
				}else{
					reg = reg + ","+ datos.get(i);
				}
				System.out.println("no esta bacio"+datos);
			}
			
		}else{
			System.out.println("esta vacio");
		}
		
		return reg; 
	}
	
	
}
